Pull highway data from OpenStreetMap as shapefile

This notebook pulls highway line data from the OpenStreetMap database and creates a shapefile containing the query results.

Required packages

Variable settings

bounding_box_filepath — path to shapefile to can define the desired bounding box to query the OpenStreetMap database
result_shapefile_filepath — path to export shapefile containing the query results


In [1]:
bounding_box_file = ""

In [2]:
result_shapefile_filepath = ""

Import statements


In [3]:
import overpy
import fiona

Utility functions

function to see what results were returned from the Overpass API query


In [5]:
def print_results(results):
    for way in result.ways:
        print("Name: %s" % way.tags.get("name", "n/a"))
        print("  Highway: %s" % way.tags.get("highway", "n/a"))
        print("  Nodes:")
        for node in way.nodes:
            print("    Lat: %f, Lon: %f" % (node.lat, node.lon))

Query OpenStreetMap using OverpassAPI via overpy python package

setup Overpass api


In [6]:
api = overpy.Overpass()

define bounding box from a 1km-buffered envelope around the study area boundary


In [7]:
with fiona.open(bounding_box_file, mode='r') as bounding_box:
    bounds = bounding_box.bounds
    bounding_box.close()

In [8]:
print(bounds)


(11.290198256852443, 47.202364564149754, 11.470060257137265, 47.306229150962515)

define query


In [9]:
query = """way({bottom},{left},{top},{right}) ["highway"]; (._;>;); out body;""".format(bottom=bounds[1],
                                                                                        left=bounds[0],
                                                                                        top=bounds[3],
                                                                                        right=bounds[2])

execute query


In [10]:
result = api.query(query)

Write OpenStreetMap data to a shapefile


In [11]:
from fiona.crs import from_epsg
schema = {'geometry': 'LineString', 'properties': {'Name':'str:80', 'Type':'str:80'}}
with fiona.open(result_shapefile_filepath, 'w', crs=from_epsg(4326), driver='ESRI Shapefile', schema=schema) as output:
    for way in result.ways:
        # the shapefile geometry use (lon,lat) 
        line = {'type': 'LineString', 'coordinates':[(node.lon, node.lat) for node in way.nodes]}
        prop = {'Name': way.tags.get("name", "n/a"), 'Type': way.tags.get("highway", "n/a")}
        output.write({'geometry': line, 'properties':prop})
    output.close()